<!-- 我的echarts组件 -->
<template>
	<div ref="mChartRef" class="m-chart-wp" :style="{height: height}">
		<div class="m-chart" ref="chartRef"></div>
	</div>
</template>
<script>
import * as echarts from 'echarts';
export default {
	props: {
		height: {
			type: String,
			default: '100%'
		},
		options: {
			type: Object
		},
		on: {
			type: [Object, null],
			default: () => (null)
		},
		wait: {
			type: Number,
			default: 0
		}
	},
	data() {
		return {
			timer: null,
			myChart: null,
		}
	},
	watch: {
		options: {
			handler: function (val, oldVal) {
				this.initChart();
			},
			deep: true
		}
	},
	mounted() {
		if(!this.wait) {
			this.initChart();
		} else {
			setTimeout(() => {
				this.initChart();
			}, this.wait);
		}
		// 监听尺寸变化
		window.addEventListener('resize', this.debResize);
	},
	beforeDestroy() {
		if(this.myChart) {
	    this.myChart.dispose();
	    this.myChart = null;
		}

		// 移除页面尺寸监听
		clearTimeout(this.timer);
		window.removeEventListener('resize', this.debResize);
	},
	methods: {
		initChart() {
			if(!this.options) {
				return;
			}
			if(!this.myChart && this.$refs.chartRef) {
				this.myChart = echarts.init(this.$refs.chartRef);
				// 监听事件
				if(this.on) {
					for(let key in this.on) {
						this.myChart.on(key, this.on[key]);
					}
				}
			}
			if(this.myChart) {
				this.myChart.setOption(this.options, true);
			}
	  },

		debResize() {
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				if(this.myChart) {
					this.myChart.resize();
				}
			}, 100);
		}
	}
}
</script>
<style lang="scss" scoped>
.m-chart-wp {
	width: 100%;
	.m-chart {
		width: 100%;
		height: 100%;
	}
}
</style>